<template>
  <div class="category-manage">
    <el-card>
      <div class="card-header">
        <h2>菜品分类管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增分类
        </el-button>
      </div>

      <!-- 分类列表表格 -->
      <el-table :data="categoryList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
// 导入API请求方法（需确保路径正确）
import { getCategories, addCategory, updateCategory, deleteCategory } from '../api/category';

// 分类列表数据
const categoryList = ref([]);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新增分类');

// 表单数据
const form = reactive({
  id: null,
  name: '',
  status: 1 // 默认启用
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 32, message: '分类名称长度在1-32个字符之间', trigger: 'blur' }
  ]
};

const formRef = ref(null);

// 获取分类列表
const loadCategoryList = async () => {
  try {
    const response = await getCategories();
    if (response.code === 200) {
      categoryList.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取分类列表失败');
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    ElMessage.error('获取分类列表失败');
  }
};

// 新增分类
const handleAdd = () => {
  form.id = null;
  form.name = '';
  form.status = 1;
  dialogTitle.value = '新增分类';
  dialogVisible.value = true;
};

// 编辑分类
const handleEdit = (row) => {
  form.id = row.id;
  form.name = row.name;
  form.status = row.status;
  dialogTitle.value = '编辑分类';
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    let response;
    if (form.id) {
      // 编辑操作
      response = await updateCategory(form.id, form);
    } else {
      // 新增操作
      response = await addCategory(form);
    }

    if (response.code === 200) {
      ElMessage.success(form.id ? '分类更新成功' : '分类新增成功');
      dialogVisible.value = false;
      loadCategoryList(); // 重新加载列表
    } else {
      ElMessage.error(response.msg || (form.id ? '更新失败' : '新增失败'));
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('提交失败:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 删除分类
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除该分类吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    const response = await deleteCategory(id);
    if (response.code === 200) {
      ElMessage.success('分类删除成功');
      loadCategoryList(); // 重新加载列表
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除操作失败');
    }
  }
};

// 页面初始化时加载数据
onMounted(() => {
  loadCategoryList();
});
</script>

<style scoped>
.category-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}
</style>